package com.sntk.organauthomanager.infrastructure.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
//import org.springframework.boot.context.properties.ConfigurationProperties;
//import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @ClassName: JwtUtil
 * @author: wgchao
 * @createTime: 2020/5/9 3:11 PM
 * @Description: token工具
 */
@Component
//@RefreshScope
public class JwtUtil {
    //盐
    @Value("${jwt.config.key}")
    private String key ;
    //过期时间
    @Value("${jwt.config.ttl}")
    private long ttl ;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public long getTtl() {
        return ttl;
    }

    public void setTtl(long ttl) {
        this.ttl = ttl;
    }


    /**
     * 生成JWT
     * @param uname 账户名uname
     * @param subject 机构编号
     * @param type 申请类型 local/service/external
     * @return
     */
    public String createJWT(String uname, String subject, String type) {
        //signWith(SignatureAlgorithm.HS256, key) 设置加密方式，和盐 。盐自己规定
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder().setId(uname)
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key)
                .claim("type", type);
        if (ttl > 0) {
            //设置过期时间
            builder.setExpiration(new Date( nowMillis + ttl));
        }
        return builder.compact();
    }

    /**
     * 解析JWT
     * @param jwtStr
     * @return
     */
    public Claims parseJWT(String jwtStr){
        return  Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwtStr)
                .getBody();
    }
}
